package org.shopping;


import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
        import java.sql.*;

@WebServlet(name = "Userupdate", value = "/UserUpdateServlet")
public class UserUpdateServlet extends HttpServlet {
    // 数据库连接参数
    private static final String DB_URL = "jdbc:mysql://localhost:3306/shopping?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "root";

    // 连接数据库
    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
    }

    // 处理 POST 请求
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求参数

        HttpSession session = request.getSession();
        int customerId= (int) session.getAttribute("customer_id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");

        // 设置响应内容类型为 JSON
        response.setContentType("text/html; charset=UTF-8");

        PrintWriter out = response.getWriter();

        // 校验输入数据
        if (username == null || password == null || phone == null || username.isEmpty() || password.isEmpty() || phone.isEmpty()) {
            out.print("{\"message\":\"用户名、密码和手机号不能为空！\"}");
            out.flush();
            return;
        }

        // 校验手机号格式
        if (!phone.matches("^\\d{11}$")) {
            out.print("{\"message\":\"手机号格式无效，必须是11位数字！\"}");
            out.flush();
            return;
        }

        // 更新数据库中的用户信息
        try (Connection conn = getConnection()) {
            // 检查用户是否存在
            String checkUserQuery = "SELECT * FROM customers WHERE username = ?";
            try (PreparedStatement psCheck = conn.prepareStatement(checkUserQuery)) {
                psCheck.setString(1, username);
                ResultSet rs = psCheck.executeQuery();
                if (rs.next()) {
                    out.print("<script>alert('用户名已存在！');history.back();</script>");
                    out.flush();
                    return;
                }
            }

            // 更新用户信息
            String updateQuery = "UPDATE customers SET password = ?, phone = ? , username = ? WHERE customer_id = ?";
            try (PreparedStatement psUpdate = conn.prepareStatement(updateQuery)) {
                psUpdate.setString(1, password);
                psUpdate.setString(2, phone);
                psUpdate.setString(3, username);
                psUpdate.setInt(4, customerId);
                int rowsAffected = psUpdate.executeUpdate();

                if (rowsAffected > 0) {
                    out.print("<script>alert('修改成功！');history.back();</script>");
                } else {
                    out.print("<script>alert('更新失败，请稍后再试！');history.back();</script>");
                }
                out.flush();
            }

        } catch (SQLException e) {
            e.printStackTrace();
            out.print("<script>alert('内部服务器错误！');history.back();</script>");
            out.flush();
        }
    }
}
